/**
 * @file date-range
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import {
  FormControl,
  InputGroup,
  Button
} from 'react-bootstrap';
import './date.scss';
import * as DateTimePicker from 'react-datetime';
import {Overlay} from 'react-bootstrap';
import SimplePopOver from '../simple-popover/simple-popover';
import {getDialogContainer} from '../../util/helper';

import * as moment from 'moment';
import * as cx from 'classnames';
const noop = () => {};

export default class MyDateTime extends PureComponent
{
  static propTypes = {
    className: PropTypes.string,
    onChange: PropTypes.func.isRequired
  };

  static defaultProps = {
    inputProps: {},
    format: 'X',
    mode: 'datetime',
    onChange: value => console.log(value)
  };

  constructor(props) {
    super(props);

    this.getOffset = this.getOffset.bind(this);
    this.open = this.open.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.close = this.close.bind(this);
    this.clearValue = this.clearValue.bind(this);
    this.checkIsValidDate = this.checkIsValidDate.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.state = {
      open: false
    };
  }
  clearValue() {
    this.props.onChange('');
  }

  checkIsValidDate(currentDate, selectedDate) {
    const {
      minDate,
      maxDate
    } = this.props;

    if (minDate && currentDate.isBefore(minDate, 'day')) {
      return false;
    } else if (maxDate && currentDate.isAfter(maxDate, 'day')) {
      return false;
    }

    return true;
  }

  open() {
    this.setState({
      open: true
    });
  }

  close() {
    this.setState({
      open: false
    });
  }

  handleFocus(e) {
    e.stopPropagation();
    this.open();
  }

  handleChange(value) {
    const {
      onChange,
      format,
      mode,
      minTime,
      maxTime
    } = this.props;

    if (minTime && value && value.isBefore(minTime, 'second')) {
      value = minTime;
    } else if (maxTime && value && value.isAfter(maxTime, 'second')) {
      value = maxTime;
    }

    onChange(value.format(format));
    mode === 'date' && this.close();
  }

  getOffset(box) {
    const dom = findDOMNode(this).getBoundingClientRect();
    let x =  (dom.width - box.width) / 2;

    return {
      x,
      y: 10
    }
  }

  render() {
    const {
      format,
      value,
      inputFormat,
      inputProps,
      minDate,
      maxDate,
      mode,
      disabled,
      timeFormat,
      className,
      timeConstraints,
      style
    } = this.props;
    const open = this.state.open;

    const viewValue = value ? moment(value, format).format(inputFormat) : '';
    const parts = inputFormat.split(' ');

    return (
      <InputGroup className={cx('date-time', className)} style={style}>
        <FormControl
          {...inputProps}
          disabled={disabled}
          type="text"
          value={viewValue}
          className="text-date"
          onChange={noop}
          onClick={this.handleFocus}
        />
        {value && !disabled &&(
            <span
              className="text-date-delete"
              onClick={this.clearValue}
            >
               <i className="fa fa-times v-middle"/>
            </span>
          )
        }
        <InputGroup.Button>
          <Button
            disabled={disabled}
            onClick={this.open}
          >
            <i className="glyphicon glyphicon-calendar" />
          </Button>
        </InputGroup.Button>

        {open ? (
          <Overlay
            placement="bottom"
            target={() => findDOMNode(this)}
            onHide={this.close}
            container={() => findDOMNode(this)}
            rootClose
            show
          >
            <SimplePopOver className="date-time-picker-popover" offset={this.getOffset}>
              <DateTimePicker
                input={false}
                value={moment(value, format)}
                dateFormat={mode === 'time' ? false : parts[0]}
                timeFormat={timeFormat || (mode === 'date' ? false : '时间：HH:mm')}
                onChange={this.handleChange}
                minDate={minDate}
                maxDate={maxDate}
                isValidDate={this.checkIsValidDate}
                timeConstraints={timeConstraints || {
                  minutes: {
                    step: 1
                  }
                }}
                canDelete
                utc
              />
            </SimplePopOver>
          </Overlay>
        ) : null}

      </InputGroup>
    );
  }
}
